<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '注册页面',
  },
}
</route>
<template>
  <!-- <view
    class="bg-white overflow-hidden pt-2 px-4"
    :style="{ marginTop: safeAreaInsets?.top + 'px' }"
  ></view> -->
  <!-- 背景图片 -->
  <view class="background">
    <!-- 顶部LOGO以及标题 -->
    <view class="top-container">
      <view class="logo"></view>
      <view class="logo-bottom"></view>
      <view class="container-title">灵活用工管理系统</view>
      <view class="title-underline"></view>
      <!-- 新增的实线 -->
    </view>
    <!-- 中间输入框 -->
    <view class="middle-form-container">
      <view class="middle_form_line">
        <view class="middle_form_lineLable-name"></view>
        <view class="middle_form_lineInput">
          <input class="uni-input" placeholder="请输入您的姓名" type="text" v-model="name" />
        </view>
      </view>
      <!-- <view class="middle_form_line">
        <view class="middle_form_lineLable-cellicon"></view>
        <view class="middle_form_lineInput">
          <input class="uni-input" placeholder="请输入您的手机号码" type="text" v-model="cell" />
        </view>
      </view> -->
      <view class="middle_form_line">
        <view class="middle_form_lineLable-cellicon"></view>
        <view class="middle_form_lineInput">
          <input
            class="uni-input"
            type="text"
            placeholder="请输入您的身份证号码"
            v-model="idnumber"
          />
          <span v-if="showError" class="error-message">身份证号码不正确</span>
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-container">
      <!-- <view class="bottom-container-title">请务必填写您本人实名认证的手机号码</view> -->
      <view class="flex items-center mb-2">
        <checkbox :value="agreeTerms" @click="onAgreeTermsChange" style="transform: scale(0.7)" />
        <label for="terms-agreement" style="font-size: 12px">
          我已阅读并同意
          <text class="text-blue-500 underline" @click="showUserAgreement" style="font-size: 12px">
            用户服务协议
          </text>
          和
          <text class="text-blue-500 underline" @click="showPrivacyPolicy" style="font-size: 12px">
            隐私政策
          </text>
        </label>
      </view>
      <view class="bottom-container-submit">
        <wd-button :disabled="!agreeTerms || !isValidForm" @click="submit">开始身份验证</wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {
  postVerifyIdentityAPI,
  getUserAgreementAPI,
  getPrivacyPolicyAPI,
  UserAgreementResponse,
} from '@/service/index/home'
import { useUserInfoStore } from '@/store/userInfo'
defineOptions({
  name: 'Home',
})

// 变量区
const name = ref()
const cell = ref()
const idnumber = ref()
const showError = ref(false)
const agreeTerms = ref(false)
const userInfoStore = useUserInfoStore() // 使用store

// 获取屏幕边界到安全区域距离
// const { safeAreaInsets } = uni.getSystemInfoSync()
// 初始化
onLoad(() => {})

// 身份证校验
const isValidIDNumber = (idNumber: string): boolean => {
  const idRegex = /^\d{17}[0-9X]$/i
  return idRegex.test(idNumber)
}
// 监听 idNumber 的变化
watch(idnumber, (newValue) => {
  validateIDNumber()
})

// 校验身份证号码
function validateIDNumber() {
  if (!isValidIDNumber(idnumber.value)) {
    showError.value = true
  } else {
    showError.value = false
  }
}

// 外部链接跳转
function handleNavigate(url: string) {
  wx.navigateTo({
    url: `/pagesFace/pages/webview/webview?url=${encodeURIComponent(url)}`,
  })
}

// 身份证验证成功后调用的 API 方法
const verifyIdentity = async () => {
  try {
    const response = await postVerifyIdentityAPI(name.value, cell.value, idnumber.value)
    if (response.success && response.data) {
      const url = response.data as string
      handleNavigate(url)
    }
  } catch (error) {
    console.error('身份验证错误:', error)
    // 处理错误情况
  }
}

// 监听用户同意服务协议的变化
const onAgreeTermsChange = () => {
  agreeTerms.value = !agreeTerms.value
}

// 实现身份证号码校验，正确后才会提交
const submit = () => {
  if (!agreeTerms.value) {
    uni.showToast({
      title: '请同意用户服务协议和隐私政策',
      icon: 'none',
    })
    return
  }
  if (!isValidIDNumber(idnumber.value)) {
    showError.value = true
    console.error('无效的身份证号码')
    return
  }
  // 检查所有字段是否填写
  if (!name.value || !idnumber.value) {
    uni.showToast({
      title: '请填写所有必填项',
      icon: 'none',
    })
    return
  }
  verifyIdentity() // 将callbackURL传递给verifyIdentity

  // 验证通过，保存数据到Pinia
  userInfoStore.setUserInfo(cell.value, name.value, idnumber.value)
}
// 添加表单验证状态
const isValidForm = computed(() => {
  return name.value && idnumber.value && !showError.value
})

// 类型保护函数
function isUserAgreementResponse(obj: any): obj is UserAgreementResponse {
  return (
    obj && obj.data && typeof obj.data === 'object' && 'title' in obj.data && 'content' in obj.data
  )
}
// 显示用户服务协议
const showUserAgreement = async () => {
  try {
    const response = await getUserAgreementAPI()

    // 类型保护
    if (isUserAgreementResponse(response)) {
      const { title, content } = response.data
      uni.showModal({
        title,
        content,
        showCancel: false,
      })
    } else {
      console.error('Invalid response format from getUserAgreementAPI')
    }
  } catch (error) {
    console.error('Failed to fetch user agreement:', error)
    uni.showToast({
      title: '加载用户服务协议失败',
      icon: 'none',
    })
  }
}
// 显示隐私政策
const showPrivacyPolicy = async () => {
  try {
    const response = await getPrivacyPolicyAPI()

    // 类型保护
    if (isUserAgreementResponse(response)) {
      const { title, content } = response.data
      uni.showModal({
        title,
        content,
        showCancel: false,
      })
    } else {
      console.error('Invalid response format from getPrivacyPolicyAPI')
    }
  } catch (error) {
    console.error('Failed to fetch user agreement:', error)
    uni.showToast({
      title: '加载隐私政策失败',
      icon: 'none',
    })
  }
}
</script>

<style scoped lang="scss">
::v-deep input {
  height: 60rpx;
  padding: 0 15px;
  line-height: 90rpx;
  background-color: transparent !important;
  border: 5rpx solid #1989fa;
}
::v-deep input {
  color: #000;
}
.main-title-color {
  color: #000;
}
// 背景图片
.background {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-image: url('http://hrise.heartful.com.cn/heartful/assets/loginbg.png');
  background-repeat: no-repeat;
  background-position: center;
}
// 顶部区域
.top-container {
  position: relative;
  display: flex; /* 添加 */
  flex-direction: column; /* 添加 */
  align-items: center; /* 可选，使元素水平居中 */
  width: auto;
  height: 200px;
  margin-top: 50px;
}
// LOGO
.logo {
  position: absolute; /* 使用绝对定位 */
  top: -10px; /* 使 logo 向上移动 5px */
  width: 55px;
  height: 80px;
  background-image: url('http://hrise.heartful.com.cn/heartful/assets/top.png');
  background-repeat: no-repeat;
  background-position: center;
}
.logo-bottom {
  width: 280px;
  height: 170px;
  background-image: url('http://hrise.heartful.com.cn/heartful/assets/bottom.png');
  background-repeat: no-repeat;
  background-position: center;
}
// 小程序标题
.container-title {
  font-size: 24px;
  line-height: 15px;
  color: #277ef9;
}
.title-underline {
  width: 100%; /* 实线宽度 */
  height: 3px; /* 实线高度 */
  margin-top: 15px; /* 实线与文字之间的间距 */
  background-color: #1d78fa; /* 实线颜色 */
}
// 中间输入框
.middle-form-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0 120rpx;
  margin-top: 15px;
}
.middle_form_line {
  display: flex;
  margin-top: 40rpx;
  line-height: 35px;
}
.middle_form_lineLable-name {
  width: 15%;
  height: 70rpx;
  background-image: url('http://hrise.heartful.com.cn/heartful/wechat/name.png');
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  transform: scale(1.2); /* 放大 1.2 倍 */
}
.middle_form_lineLable-cellicon {
  position: relative;
  display: inline-block;
  width: 15%;
  height: 70rpx;
  vertical-align: bottom; /* 底部对齐 */
  background-image: url('http://hrise.heartful.com.cn/heartful/wechat/cellicon.png');
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  transform: scale(1.2); /* 放大 1.2 倍 */
}
.middle_form_lineInput {
  display: inline-block;
  width: 60%;
  border: 1px solid #ccc; /* 示例边框 */
}
// 底部按钮
.bottom-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
}
.bottom-container-title {
  font-size: 14px;
  font-weight: 600;
  color: #1d78fa;
}
.bottom-container-submit {
  margin-top: 20px;
}
.error-message {
  font-size: 12px;
  color: red;
}
</style>
